package com.itheima.abvice;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
public class RecordLogAdivce {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(log)")
    public Object recordLog(ProceedingJoinPoint pjp, LogOperation log) throws Throwable {
        //原方法执行之间的时间
        long begin = System.currentTimeMillis();
        Object retureValue = pjp.proceed();
        //原方法执行之后的时间
        long end = System.currentTimeMillis();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(getCurrentEmpId());
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(pjp.getTarget().getClass().getName());
        operateLog.setMethodName(signature.getMethod().getName());
        operateLog.setMethodParams(pjp.getArgs()==null?"": pjp.getArgs().toString());
        operateLog.setReturnValue(retureValue==null?"":retureValue.toString());
        operateLog.setCostTime(end-begin);
        operateLogMapper.insert(operateLog);
        return retureValue;
    }

    private Integer getCurrentEmpId() {
        return 1;
    }
}
